<?php namespace Admin\Model;

use Hdphp\Model\Model;

//节点表
class Node extends Model{
	//定义模型
	protected $table = "node";

	//自动验证
	protected $validate = [
		['name','required','节点名不能为空',3,3],
		['title','required','节点描述不能为空',3,3],
		['status','required','节点状态不能为空',3,3],
		['sort','required','排序不能为空',3,3],
		['sort','num:0,999','排序只能为3位数字',3,3],
	];

	//自动完成
	protected $auto = [
		['level','getlevel','method',3,3],
	];

	//获得节点层级
	public function getlevel(){
		$pid=Q('post.pid',0,'intval');
		if ($pid) {
			$parlevel=$this->where("id={$pid}")->pluck('level');
			return $parlevel+1;
		}
		return 1;
	}

	//添加节点
	public function store(){
		// p(Q('post.'));die;
		if (!$this->create()) return false;
		$this->add();
		Cache::del('allRole');
		return true;
	}

	//修改节点
	public function edit(){
		if(!$this->create()) return false;
		$this->save();
		Cache::del('allRole');
		return true;
	}

	//获得所有节点的树状结构
	public function getTree($data=[]){
		if ($data) {
			return Data::tree($data,'name','id','pid');
		}
		return Data::tree($this->get(),'name','id','pid');
	}

	//获得多级目录列表
	public function getchannelLevel(){
		return Data::channelLevel($this->get(),0,"&nbsp;",'id','pid');
	}

	//获得除了自己和自己子集的所有数据
	public function getNoMy($id){
		//获得自己所有子集的id
		$ids=$this->getSon($id);
		//压入自己的id
		$ids[]=$id;
		$ids=implode(',',$ids);
		//查询数据
		return $this->where("id not in ({$ids})")->get();
	}

	//获得自己所有子集的id
	public function getSon($id){
		$tmp=[];
		foreach ($this->get() as $v) {
			if($v['pid']==$id){
				$tmp[]=$v['id'];
				$tmp=array_merge($tmp,$this->getSon($v['id']));
			}
		}
		return $tmp;
	}

	//重新排序
	public function reSort(){
		$data=Q('post.');
		foreach ($data['id'] as $k => $v) {
			$this->where("id=$v")->update(['sort'=>$data['sort'][$k]]);
		}
	}


}